
//引入封装好的接口
import { specslist, specscount } from '../../../request/api'
interface specsList {
    specsList: Array<object>
}
interface StateSize {
    size: number
}
interface StateCount {
    count: number
}
interface StatePage {
    page: number
}

const state = {
    specsList: [],
    size: 3,//页面显示的条数
    page: 1, //页码初始值
    count: 0  //总数
}
const getters = {
    getSpecsList(state: specsList) {
        return state.specsList
    },
    //返回总数
    getCount(state:StateCount) {
        return state.count
    },
    //返回当前显示条数
    getSize(state:StateSize) {
        return state.size
    }
}
const mutations = {
    REQ_SPECSLIST(state:specsList, payload:any) {
        state.specsList = payload
    },
    REQ_GETCOUNT(state:StateCount, payload:any) {
        state.count = payload
    },
    //修改页码
    CHANGE_PAGE(state:StatePage, payload:any) {
        state.page = payload
    }
}
const actions = {
    //封装一个获取规格列表的行动
    getSpecsListAction(context:any) {
        specslist({
            size: context.state.size,
            page: context.state.page
        })
            .then((res:any) => {
                if (res.code == 200) {
                    context.commit('REQ_SPECSLIST', res.list)
                    if (context.state.page != 1 && res.list.length == 0) {
                        context.dispatch('changePageAction', context.state.page - 1)
                    }
                }
            })
    },
    //封装一个获取总数的行动
    getCountAction(context:any) {
        specscount()
            .then((res:any) => {
                // console.log(res,'总数哈哈哈');
                if (res.code == 200) {
                    context.commit('REQ_GETCOUNT', res.list[0].total)
                }
            })
    },
    //封装一个切换页码的行动
    changePageAction(context:any, payload:any) {
        //第一、当用户切换页码，我们要修改page
        context.commit('CHANGE_PAGE', payload)
        //第二、重新调用列表
        context.dispatch('getSpecsListAction')
    }
}


export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}